package com.zyx.flinkdemo.stream.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.flink.api.java.tuple.Tuple2;

import java.util.List;

/**
 * @author zyx
 * @since   2021/2/5
 * Desc: 用于维度查询的工具类  底层调用的是Util
 * select * from dim_base_trademark where id=10 and name=zs;
 *
 */
public class DimUtil {
    /**
     * 从Phoenix中查询数据，没有使用缓存
     * @param tableName Phoenix中的表名
     * @param cloNameAndValue
     * @return
     */
    @SafeVarargs
    public static JSONObject getDimInfoNoCache(String tableName, Tuple2<String, String>... cloNameAndValue) {
        //拼接查询条件
        StringBuilder whereSql = new StringBuilder(" where ");
        for (int i = 0; i < cloNameAndValue.length; i++) {
            Tuple2<String, String> tuple2 = cloNameAndValue[i];
            String filedName = tuple2.f0;
            String fieldValue = tuple2.f1;
            if (i > 0) {
                whereSql.append(" and ");
            }
            whereSql.append(filedName).append("='").append(fieldValue).append("'");
        }

        String sql = "select * from " + tableName + whereSql;
        System.out.println("查询维度的SQL:" + sql);
        List<JSONObject> dimList = PhoenixUtil.queryList(sql, JSONObject.class);
        JSONObject dimJsonObj = null;
        //对于维度查询来讲，一般都是根据主键进行查询，不可能返回多条记录，只会有一条
        if (dimList.size() > 0) {
            dimJsonObj = dimList.get(0);
        } else {
            System.out.println("维度数据没有找到:" + sql);
            System.out.println();
        }
        return dimJsonObj;
    }
}
